<template>
  <CommonDialog
    v-model="visible"
    :loading="loading"
    :title="`${dictionaryId ? '编辑' : '添加'}插件`"
    :width="500"
    @submit="submit"
    @cancel="cancel"
  >
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="80">
      <FormItem label="名称" prop="name">
        <Input v-model="formData.name" placeholder="请输入名称" />
      </FormItem>

      <FormItem label="描述" prop="description">
        <Input
          v-model="formData.description"
          type="textarea"
          :rows="8"
          placeholder="请输入描述"
        />
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { ref } from 'vue'
import { Message } from 'view-ui-plus'

import { createPlugin, updatePlugin, detailPlugin } from '@/api/modules/plugin'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

// 元数据ID
const modelId = ref(undefined)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  name: '', //名称
  description: '' //描述
})

// 表单校验条件
const rules = ref({
  name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
  description: [{ required: true, message: '请选择描述', trigger: 'blur' }]
})

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    const params = {
      ...formData.value,
      id: modelId.value
    }

    await (modelId.value ? updatePlugin : createPlugin)({
      data: {
        ...params,
        parentid: 0,
        id: modelId.value
      }
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const getDetailData = () => {
  loading.value = true

  detailPlugin({
    data: {
      id: modelId.value
    }
  })
    .then(({ data }) => {
      for (const key in formData.value) {
        formData.value[key] = data[key]
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 初始化对话框
 */
const initDialog = (id) => {
  // 显示对话框
  visible.value = true

  modelId.value = id

  if (id) {
    getDetailData()
  }
}

defineExpose({
  initDialog
})
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}
.ivu-input-wrapper,
.ivu-select {
  width: 360px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}

.ivu-upload {
  display: inline-block;
  .upload-box {
    width: 156px;
    height: 156px;
    line-height: 156px;
  }
}
.ivu-select-item {
  display: flex;
  align-items: center;
  .menu-item-title {
    font-size: 16px;
    margin-left: 10px;
  }
  .menu-item-icon {
    width: 20px;
    height: 20px;
  }
}
</style>
